import { message, Image, Select, Card } from 'antd';
import React, { useState, useRef, useEffect } from 'react';
import { PageContainer } from '@ant-design/pro-layout';
import type { ProColumns, ActionType } from '@ant-design/pro-table';
import ProTable from '@ant-design/pro-table';
import { GetMpConfigList, create_mp_config, update_mp_config } from './service';
import type { AddConfigItem, TableListItem, TableListPagination } from './data';
import CreateForm from './components/CreateForm';
import { useLocation } from 'react-router';
import { Color } from '@antv/l7-react/lib/component/LayerAttribute';

/**
 * 添加配置
 *
 * @param fields
 */
const { Meta } = Card;

const handleAdd = async (fields: AddConfigItem) => {
  const hide = message.loading('正在添加');
  try {
    if (fields.Id === undefined) {
      await create_mp_config({ ...fields });
    } else {
      await update_mp_config({ ...fields });
    }
    hide();
    message.success('添加成功');
    return true;
  } catch (error) {
    hide();
    message.error('添加失败请重试！');
    return false;
  }
};

interface InitCorpDataType {
  value: string;
  label: string;
}

const TableList: React.FC = () => {
  /** 新建窗口的弹窗 */
  const [createModalVisible, handleModalVisible] = useState<boolean>(false);

  const [showDetail, setShowDetail] = useState<boolean>(false);
  const actionRef = useRef<ActionType>();
  const [currentRow, setCurrentRow] = useState<TableListItem>();
  const [selectedRowsState, setSelectedRows] = useState<TableListItem[]>([]);
  /** 国际化配置 */

  const [corpIdConfig, setCorpIdConfig] = useState(CORP_ID);

  const [initCorp, setInitCorp] = useState<InitCorpDataType[]>([]);

  const location = useLocation();
  const searchParams = new URLSearchParams(location.search);

  const configId = searchParams.get('config_id');
  const [useConfigId, setUseConfigId] = useState<string>('');

  useEffect(() => {
    // todo 获取企业微信配置列表
    setInitCorp([{ value: CORP_ID, label: '我的企业' }]);
    // 设置默认搜索条件
    setCorpIdConfig(CORP_ID);
    if (configId) {
      handleModalVisible(true);
      setUseConfigId(configId);
    }
  }, []);

  const { Option } = Select;
  const columns: ProColumns<TableListItem>[] = [
    {
      title: '配置描述',
      dataIndex: 'title',
      tip: '描述配置的详情',
      search: false,
    },
    {
      title: '添加客服页面',
      dataIndex: 'content',
      valueType: 'textarea',
      width: 300,
      render: (dom, entity) => {
        return (
          <Card style={{ width: 250, margin: 0 }} loading={false} size="small">
            <Meta title={entity.content.split('#')[0]} />
            {/* <Image
              width={200}
              src="https://ybk-fund-store.oss-cn-chengdu.aliyuncs.com/zhonghui/file/20230218/9f2efb08-da1b-44d1-a76b-3612eb2e63c8.jpg"
            /> */}
            <Meta description={'副标题：' + entity.content.split('#')[1]} />
            {/* <Image
              width={200}
              src="https://ybk-fund-store.oss-cn-chengdu.aliyuncs.com/zhonghui/file/20230218/c040fe1c-aaa8-4283-b957-87a16df7c92f.jpg"
            /> */}
            <Meta description={'尾描述：' + entity.content.split('#')[2]} />
          </Card>
        );
      },
      search: false,
    },
    {
      title: '保障卡页面',
      dataIndex: 'guarantee',
      valueType: 'textarea',
      width: 300,
      render: (dom, entity) => {
        return (
          <Card style={{ width: 250, margin: 0 }} loading={false} size="small">
            <Meta title={entity.guarantee.split('#')[0]} />
            {/* <Image
              width={200}
              src="https://ybk-fund-store.oss-cn-chengdu.aliyuncs.com/zhonghui/file/20230218/8e377768-8ed3-4f7b-938f-15408292a7c8.jpg"
            /> */}
            <Meta description={'副标题：' + entity.guarantee.split('#')[1]} />
            {/* <Image
              width={200}
              src="https://ybk-fund-store.oss-cn-chengdu.aliyuncs.com/zhonghui/file/20230218/b16ed9a0-ddbe-4a33-be76-4df20e46b1c1.jpg"
            /> */}
            <Meta description={'尾描述：' + entity.guarantee.split('#')[2]} />
          </Card>
        );
      },
      search: false,
    },
    {
      title: '企业id',
      dataIndex: 'corpid',
      valueType: 'textarea',
      copyable: true,
      ellipsis: true,
      initialValue: corpIdConfig,
      renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
        if (type === 'form') {
          return null;
        }
        return (
          <Select placeholder="请选择一个要查询的企业" {...rest}>
            {initCorp.map((node) => (
              <Option key={node.value} value={node.value}>
                {node.label}
              </Option>
            ))}
          </Select>
        );
      },
    },
    {
      title: '配置码',
      dataIndex: 'config_id',
      valueType: 'textarea',
      copyable: true,
      ellipsis: true,
      // renderFormItem: (item, { type, defaultRender, ...rest }, form) => {
      //   if (type === 'form') {
      //     return null;
      //   }

      //   return (
      //     <Select placeholder="请选择一个要查询的企业" {...rest}>
      //       {/* {initCorp.map((node) => (
      //         <Option key={node.value} value={node.value}>
      //           {node.label}
      //         </Option>
      //       ))} */}
      //     </Select>
      //   );
      // },
    },
    {
      title: '状态',
      dataIndex: 'status',
      hideInForm: true,
      valueEnum: {
        valid: {
          text: '生效中',
          status: 'valid',
        },
        invalid: {
          text: '已停用',
          status: 'invalid',
        },
      },
      search: false,
    },
    {
      title: '操作',
      dataIndex: 'option',
      valueType: 'option',
      render: (_, record) => [
        <a
          key="subscribeAlert"
          onClick={() => {
            handleModalVisible(true);
            setCurrentRow(record);
            setUseConfigId(record.config_id);
          }}
        >
          更新配置
        </a>,
      ],
    },
  ];

  return (
    <PageContainer>
      <ProTable<TableListItem, TableListPagination>
        headerTitle="配置详情"
        actionRef={actionRef}
        rowKey="id"
        search={{ labelWidth: 'auto' }}
        request={(params) => GetMpConfigList(params)}
        columns={columns}
        pagination={{
          pageSize: 10,
        }}
      />

      {/* 新建配置 */}
      <CreateForm
        createModalVisible={createModalVisible}
        handleModalVisible={handleModalVisible}
        corpId={corpIdConfig}
        configId={useConfigId}
        onSubmit={async (value) => {
          value.corp_id = corpIdConfig;
          if (currentRow?.id !== undefined) {
            value.Id = currentRow?.id;
          }
          value.content = value.main_title + '#' + value.sub_title + '#' + value.footer;
          value.guarantee = value.g_main_title + '#' + value.g_sub_title + '#' + value.g_footer;
          const success = await handleAdd(value as AddConfigItem);
          if (success) {
            handleModalVisible(false);
            if (actionRef.current) {
              actionRef.current.reload();
            }
          }
        }}
      />

      {/* <Drawer
        width={800}
        open={showDetail}
        onClose={() => {
          setCurrentRow(undefined);
          setShowDetail(false);
        }}
        closable={false}
      >
        {currentRow?.title && (
          <ProDescriptions<TableListItem>
            column={2}
            title={currentRow?.title}
            request={async () => ({
              data: currentRow || {},
            })}
            params={{
              id: currentRow?.title,
            }}
            columns={columns as ProDescriptionsItemProps<TableListItem>[]}
          />
        )}
      </Drawer> */}
    </PageContainer>
  );
};

export default TableList;
